package com.meixiang.fragment.coupon;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.CouponActivity;
import com.meixiang.adapter.CouponAdapter;
import com.meixiang.entity.coupon.CouponEntity;
import com.meixiang.entity.coupon.CouponResultEntity;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 优惠券--过期
 * author：wangzuzhen on 2016/5/7 0007 11:30.
 */
@SuppressLint("ValidFragment")
public class OverdueFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    @Bind(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private View view;
    private CouponAdapter adapter;
    private String type="2"; //过期
    private String fromCode ;
    private int pageNo = 1;
    private int pageSize = 10 ;
    private int totalPage = 1 ;
    private CouponResultEntity couponResult ;
    private List<CouponEntity> mCouponList ;
    private boolean isLoadMore = false ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            fromCode = getArguments().getString(CouponActivity.FROMCODE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_coupon, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {}

    @Override
    protected void initView() {
        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setOnRefreshListener(this);
        mSwipeTarget.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        adapter = new CouponAdapter(getActivity(), getActivity(),fromCode,type);
        mSwipeTarget.setAdapter(adapter);
        //RecyclerView滑到底部自动加载更多
        mSwipeTarget.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });

    }

    @Override
    protected void setData() {
        showLoading();
        getOverdueCoupont();

    }

    /**
     * 获取过期优惠券数据
     */
    private void getOverdueCoupont() {
        HttpParams params = new HttpParams();
        params.put("couponIsused",type);
        params.put("pageSize",String.valueOf(pageSize));
        params.put("pageNo",String.valueOf(pageNo));
        HttpUtils.post(Config.COUPON_LIST, CouponActivity.TAG, params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                totalPage = Integer.parseInt(result.optString("totalPage"));
                couponResult = new Gson().fromJson(result.toString(),CouponResultEntity.class);
                if(couponResult!=null&& couponResult.getCouponList().size()!=0) {
                    removeStatus();
                    if(isLoadMore){
                        mCouponList.addAll(couponResult.getCouponList());
                        adapter.refreshCouponData(mCouponList);
                    }else{
                        mCouponList = couponResult.getCouponList();
                        adapter.refreshCouponData(mCouponList);
                    }
                }else{
                    showNoData("暂无数据");
                }
            }
            @Override
            public void onError(String code, String message) {
                showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoading();
                        getOverdueCoupont();
                    }
                });
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onComplete(mRefresh);
            }
        });
    }

    @Override
    public void onLoadMore() {
        pageNo ++ ;
        isLoadMore = true ;
        if(pageNo >totalPage){
            AbToastUtil.showToast(getActivity(),"已没有更多数据");
            onComplete(mRefresh);
        }else{
            getOverdueCoupont();
        }
    }

    @Override
    public void onRefresh() {
        pageNo = 1 ;
        isLoadMore = false ;
        getOverdueCoupont();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public static OverdueFragment getIntance(Bundle bundle){
        OverdueFragment overdueFragment = new OverdueFragment();
        overdueFragment.setArguments(bundle);
        return overdueFragment;
    }

}
